import React, { memo, useCallback, useMemo } from 'react';
import { Select, Tag, Badge } from 'antd';
import { FolderOutlined } from '@ant-design/icons';
import type { ICourseCategorySelectorProps } from '@/types/components/courseCategory';
import { CourseCategoryStatusEnum } from '@/types/course';
import styles from './CourseCategorySelector.module.css';

const { Option } = Select;

/**
 * 课程分类选择器组件
 * @description 用于选择课程分类，支持单选和多选模式
 */
const CourseCategorySelector: React.FC<ICourseCategorySelectorProps> = memo(({
  categories,
  selectedCategoryIds,
  onChange,
  multiple = true,
  placeholder = '请选择课程分类',
  disabled = false,
  className,
  maxCount,
  showColorIndicator = true,
  showCourseCount = false,
  courseCountMap = {}
}) => {
  // 过滤可用的分类（排除已删除和禁用的）
  const availableCategories = useMemo(() => {
    return categories
      .filter(category => category.status === CourseCategoryStatusEnum.ACTIVE)
      .sort((a, b) => a.sortOrder - b.sortOrder);
  }, [categories]);

  // 处理选择变化
  const handleChange = useCallback((value: string | string[]) => {
    const newValue = Array.isArray(value) ? value : [value];
    onChange(newValue.filter(Boolean));
  }, [onChange]);

  // 自定义标签渲染
  const tagRender = useCallback((props: any) => {
    const { label, value, closable, onClose } = props;
    const category = availableCategories.find(cat => cat.id === value);
    
    if (!category) return null;

    return (
      <Tag
        color={showColorIndicator ? category.color : undefined}
        closable={closable}
        onClose={onClose}
        className={styles.categoryTag}
      >
        {showColorIndicator && (
          <div 
            className={styles.tagColorIndicator}
            style={{ backgroundColor: category.color }}
          />
        )}
        {label}
        {showCourseCount && courseCountMap[category.id] !== undefined && (
          <Badge 
            count={courseCountMap[category.id]} 
            size="small"
            className={styles.tagBadge}
          />
        )}
      </Tag>
    );
  }, [availableCategories, showColorIndicator, showCourseCount, courseCountMap]);

  // 渲染选项
  const renderOption = (category: any) => (
    <Option key={category.id} value={category.id}>
      <div className={styles.optionContent}>
        {showColorIndicator && (
          <div 
            className={styles.colorIndicator}
            style={{ backgroundColor: category.color }}
          />
        )}
        <FolderOutlined className={styles.folderIcon} />
        <span className={styles.categoryName}>{category.name}</span>
        {showCourseCount && courseCountMap[category.id] !== undefined && (
          <Badge 
            count={courseCountMap[category.id]} 
            size="small"
            className={styles.optionBadge}
            style={{ backgroundColor: category.color }}
          />
        )}
      </div>
    </Option>
  );

  return (
    <Select
      mode={multiple ? 'multiple' : undefined}
      value={multiple ? selectedCategoryIds : selectedCategoryIds[0]}
      onChange={handleChange}
      placeholder={placeholder}
      disabled={disabled}
      className={`${styles.categorySelector} ${className || ''}`}
      allowClear
      showSearch
      filterOption={(input, option) => {
        const category = availableCategories.find(cat => cat.id === option?.value);
        return category ? 
          category.name.toLowerCase().includes(input.toLowerCase()) ||
          category.categoryCode.toLowerCase().includes(input.toLowerCase())
          : false;
      }}
      tagRender={multiple ? tagRender as any : undefined}
      maxTagCount={maxCount ? maxCount : 'responsive'}
      maxTagPlaceholder={(omittedValues) => `+${omittedValues.length}...`}
      dropdownClassName={styles.categoryDropdown}
      notFoundContent="暂无可选分类"
    >
      {availableCategories.map(renderOption)}
    </Select>
  );
});

CourseCategorySelector.displayName = 'CourseCategorySelector';

export default CourseCategorySelector;